<template>
  <div class="form-single-fragment" style="position: relative;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini" label-position="right">
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="20">
          <el-col :span="12">
            <el-form-item :label="addtitle" prop="name">
              <el-input class="input-item" v-model="ruleForm.name" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <el-cascader class="input-item" v-model="ruleForm.deptId" :clearable="true"
                           placeholder="所属部门" :loading="loading"
                           :props="dropdownprops"
                           @visible-change="onDeptIdVisibleChange" :options="dropdownList"
                           @change="onDeptIdValueChange">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="知识类型" prop="knowledgeType">
              <el-cascader v-model="ruleForm.knowledgeType"
                           ref="ref_knowledge"
                           :options="knowledgeTree"
                           :props="knowledgeProps"
                           :show-all-levels="false"
                           clearable
                           @change="knowledgeChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务类型" prop="businessType">
              <el-cascader v-model="ruleForm.businessType"
                           ref="ref_business"
                           :options="businesstypeTree"
                           :props="businesstProps"
                           :show-all-levels="false"
                           clearable
                           @change="businessChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industryType">
              <el-select v-model="ruleForm.industryType" placeholder="请选择">
                <el-option v-for="(item,index) in Industrylist" :key="index"
                           :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传附件" prop="files">
              <el-upload class="upload-demo"
                         :action="action"
                         :headers="headers"
                         :on-change="handleSuccess"
                         :on-remove="handleRemove"
                         :before-upload="beforeAvatarUpload"
                         :on-exceed="handleExceed"
                         :accept="acceptStr"
                         multiple
                         :limit="5"
                         :file-list="fileLists">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png/word/pdf/ppt文件，且不超过500MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item style="padding: 20px 0;">
              <el-button size="mini" @click="onCancel(false)">取消</el-button>
              <el-button type="primary" size="mini" @click="submitForm()">保存</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { SysDeptController } from '@/api';
import { CorporateKnowledge, fileUpload } from '@/api/knowledgeBases.js';
import { OnlineDictController } from '@/api/onlineController.js';
import { Businesstype, Knowledgetype } from '@/api/business.js';
import { getToken } from '@/utils';
export default {
  name: 'addknowledge',
  props: {
    knowledgeId: {
      default: undefined
    },
    catalogType: {
      default: undefined
    }
  },
  data () {
    return {
      action: fileUpload,
      fileLists: [],
      acceptStr: '.doc,.docx,.xls,.xlsx,.jpg,.png,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      addtitle: '',
      loading: false,
      isShowloading: false,
      userId: null,
      Industrylist: [],
      dropdownList: [],
      dropdownprops: {
        label: 'deptName',
        value: 'deptId'
      },
      knowledgeTree: [],
      knowledgeIds: [],
      knowledgeProps: {
        value: 'id',
        label: 'typeName',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      businesstypeTree: [],
      businesstypeId: [],
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      ruleForm: {
        name: '',
        deptId: '',
        knowledgeType: '',
        catalogType: '1',
        businessType: '',
        industryType: '',
        files: ''
      },
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择', trigger: 'change' }],
        knowledgeType: [{ required: true, message: '请选择', trigger: 'blur' }],
        businessType: [{ required: true, message: '请选择', trigger: 'blur' }],
        industryType: [{ required: true, message: '请选择', trigger: 'change' }],
        files: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    };
  },
  computed: {
    isEdit () {
      return this.knowledgeId != null && this.knowledgeId !== '';
    },
    headers () {
      return {
        Authorization: getToken() || ''
      };
    }
  },
  mounted () {
    this.loadknowledgeTree()
    this.loadbusinesstypeTree()
    this.loadDeptmentDropdownList()
    this.loadOnlineDictControllerData()
    this.ruleForm.catalogType = this.catalogType
    if (this.isEdit) {
      this.loadknowledgedetail()
    }
    if (this.catalogType === '1') {
      this.addtitle = '方案名称'
    } else if (this.catalogType === '3') {
      this.addtitle = '政策名称'
    } else if (this.catalogType === '4') {
      this.addtitle = '案例名称'
    }
  },
  created () {
  },
  methods: {
    /**
       * 知识库详情
       */
    loadknowledgedetail () {
      let params = this.catalogType + '/' + this.knowledgeId
      return new Promise((resolve, reject) => {
        CorporateKnowledge.detail(this, params).then(res => {
          this.ruleForm = res.data
          this.businesstypeId = [
            res.data.businessType
          ]
          this.knowledgeIds = [
            res.data.knowledgeType
          ]
          this.ruleForm.files = ''
          let file = res.data.knowledgeFileDoList
          if (file.length !== 0) {
            file.forEach((item) => {
              this.ruleForm.files += item.filePath
            })
            this.fileLists = file.map(item => {
              return {
                name: item.fileName,
                response: {
                  data: item.filePath
                }
              }
            })
          }
          this.$forceUpdate()
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
       * 所属部门下拉数据获取函数
       */
    loadDeptmentDropdownList () {
      return new Promise((resolve, reject) => {
        let params = {};
        SysDeptController.list(this, params).then(res => {
          this.dropdownList = res.data.dataList;
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
       * 所属部门下拉框显隐
       */
    onDeptIdVisibleChange (show) {

    },
    /**
       * 所属部门选中值改变
       */
    onDeptIdValueChange (value) {
      this.ruleForm.deptId = Array.isArray(value) ? value[value.length - 1] : undefined;
    },
    /**
       * 知识类型信息表树形列表
       */
    loadknowledgeTree () {
      return new Promise((resolve, reject) => {
        Knowledgetype.tree(this).then(res => {
          this.knowledgeTree = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    knowledgeChange () {
      this.$refs['ref_knowledge'].dropDownVisible = false
    },
    /**
       * 业务类型信息表树形列表
       */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this).then(res => {
          this.businesstypeTree = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    businessChange () {
      this.$refs['ref_business'].dropDownVisible = false
    },
    /**
       * 所属行业
       */
    loadOnlineDictControllerData () {
      let params = {
        dictId: '1475422753933758464'
      }
      return new Promise((resolve, reject) => {
        OnlineDictController.view(this, params).then(res => {
          this.Industrylist = JSON.parse(res.data.dictDataJson).dictData
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
       * 上传文件-成功
       */
    handleSuccess (file, fileList) {
      fileList.forEach((item, index) => {
        if (item.response && item.response.success === false) {
          this.$message({
            showClose: true,
            message: '第' + Number(index + 1) + '调数据上传失败，原因：' + item.response.errorMessage,
            type: 'error'
          });
          fileList.splice(index, 1)
        }
      })
      this.fileLists = fileList
    },
    /**
       * 上传文件-删除
       */
    handleRemove (file, fileList) {
      this.fileLists = fileList
    },
    /**
       * 上传图片限制条件
       */
    beforeAvatarUpload (file, fileList) {
      // const isJPG = file.type === 'image/jpeg'
      // const isLt500M = file.size / 1024 < 500
      // if (!isJPG) {
      //   this.$message.error('上传文件格式不对!')
      //   return false
      // }
      // if (!isLt500M) {
      //   this.$message.error('上传文件大小不能超过 500M!')
      //   return false
      // }
      // return isJPG && isLt500M
    },
    /**
       * 上传图片条数限制
       */
    handleExceed (files, fileList) {
      this.$message.warning(`最大文件上传数 5 个文件，本次上传数 ${files.length + fileList.length} 个文件，已超出限制。`);
    },
    /**
       * 提交表单
       */
    submitForm () {
      if (this.fileLists.length !== 0) {
        let filesnew = []
        this.fileLists.forEach((item) => {
          filesnew.push(item.response.data)
        })
        this.ruleForm.files = filesnew.join(',')
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          let params = this.ruleForm;
          if (this.knowledgeId) { // 修改
            return new Promise((resolve, reject) => {
              CorporateKnowledge.update(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '修改成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          } else { // 添加
            return new Promise((resolve, reject) => {
              CorporateKnowledge.add(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '添加成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
}
</script>

<style scoped>
  h3{border-bottom: 1px solid #E9E9EB;padding: 0 0 10px;}
  .table_container{margin: 10px 0;}
  .form-single-info{display: flex;justify-content: center;}
  .el-form-info{box-shadow: 0 0 10px rgba(0,0,0,0.05);padding: 20px;}
  .el-form-info strong{margin: 0 10px;}
  .el-form-info .el-time-picker{width: 100%;}
</style>
